package com.pf.utils;

import com.pf.common.dto.ExcelErrorParam;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.lang.reflect.Field;
import java.util.Set;

/**
 * 字段校验工具类
 *
 * @author PanFei
 * @version 1.0.0
 * @createTime 2022/6/25 18:48
 */
public class ValidateUtils {

    private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    /**
     * 校验excel数据
     *
     * @param rowNum
     * @param entity
     * @param groups
     * @param <T>
     */
    public static <T> ExcelErrorParam validateExcelData(int rowNum, T entity, Class<?>... groups) {
        Field[] fields = entity.getClass().getDeclaredFields();
        StringBuilder errorMsg = new StringBuilder();
        for (Field field : fields) {
            Set<ConstraintViolation<T>> constraintViolations = validator.validateProperty(entity, field.getName(), groups);
            for (ConstraintViolation constraintViolation : constraintViolations) {
                String message = constraintViolation.getMessage();
                if (StringUtils.isNotBlank(message)) {
                    errorMsg.append(message);
                }
            }
        }
        if (errorMsg.length() > 0) {
            return ExcelErrorParam.builder()
                    .rowNum(rowNum)
                    .errorMsg(errorMsg.toString())
                    .build();
        }
        return null;
    }
}
